//
// File: network.h
// Description: 
//

#ifndef NETWORK_H
#define NETWORK_H

#include <iostream>
#include <pthread.h>
#include <enet/enet.h>
#include <queue>

#define DEF_PORT 4646

using namespace std;

struct NetworkPeer {
	unsigned int address;
	unsigned short port;
	
	bool operator<(const NetworkPeer & other) const;
};
ostream & operator<<(ostream & os, const NetworkPeer & p);

struct NetworkEvent {
	enum {
		CONNECT,
		DISCONNECT,
		DATA
	} type;
	
	NetworkPeer peer;
	void *data;
};

class Network {
public:
	static Network & run();
	bool pollEvent(NetworkEvent &e);
	int size(); // Number of events in stack
	int error(); // Get current error of network
	~Network();
	
	enum NetworkError {
		NO_ERROR = 0,
		FAILED_TO_CREATE_HOST
	};

protected:
	static Network *network;
	static void *network_thread(void *param);
	
	Network(int port);
	void listen(); // listen for connections and write
		// to the event list

	queue<NetworkEvent> eventList;
	ENetAddress address;
	ENetHost *server;

	NetworkError mError;
};


#endif
